/* ---------------------------------
 *  www.ittraining.com.tw
 * --------------------------------
 */

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus.h>
#include <limits.h>
#include <signal.h>
//#define DEBUG 1

//#define PWAVE




#define LOG_CAP
//#define IT_PROJ 1
//#define LCD_OUTPUT
#define MAX_DEVICES 3
#define LOG_PERIOD 120 // 120 seconds

void dump_buf16( uint16_t *buf,int len);
void show_usage();


void reap_child(int sig);

#ifdef IT_PROJ
  pid_t buzzer_pid;
#endif

struct timeval t0,t1;
#define LOG_FILE "logb.txt"
#define LOG_FILE2 "logc.txt"
//#define LOG(time,a,b) fprintf(fp,"%010u\t%10lf\t\t%10lf\n",(unsigned int)time,a,b)
#define LOG2(time,a,b) fprintf(fp,"%12lf\t\t%12lf\n",a,b)
void do_exit(int sig);
  FILE *fp;
 FILE *fp2;
int n_master=0;
modbus_t *ctx[MAX_DEVICES];

 /*
typedef struct _palert {

  modbus_t *ctx;


} Palert;
*/



int main(int argc, char *argv[])
{
 
   
    int rc;
 
   int cnt=0;
   uint16_t rxbuf[MAX_DEVICES][64];
   short a[3],b[3];
   double fa[3],fb[3];
   unsigned long elapsed ;
   unsigned long n_second;
   int count=1;

   int p_trigger=0;
   const double MagicNumber=0.00006103;
   int i;
  // int j=0;
    errno = 0; 
   int reg_addr=100;
 
    if (argc<2) {
     show_usage();
   } 

   n_second= LOG_PERIOD*1000000;
   signal(SIGINT,do_exit);
   signal(SIGCHLD,reap_child);




    for(i=0;i<argc-1;i++) {

   ctx[i] = modbus_new_tcp(argv[i+1], 502);
 
    if (ctx[i] == NULL) {
        fprintf(stderr, "Unable to allocate modbus context\n");
        return -1;
    }


    if (modbus_connect(ctx[i]) == -1) {
        fprintf(stderr, "Connection failed: %s--%s\n",
                modbus_strerror(errno),argv[i+1]);
        modbus_free(ctx[i]);
        return -1;
    }
     #ifdef DEBUG 
   modbus_set_debug(ctx[i], TRUE);
   #endif
       n_master++;
      fprintf(stderr, "Connect Server %s Successfully\n",argv[i+1]);

  } //end crate connection
    
     fp=fopen(LOG_FILE,"w+");
     if (fp == NULL) {
        fprintf(stderr, "Unable to open file\n");
         goto close;
    }

        fp2=fopen(LOG_FILE2,"w+");
     if (fp2 == NULL) {
        fprintf(stderr, "Unable to open file\n");
         goto close;
    }

    

    /** HOLDING REGISTERS **/

    fprintf(stderr,"Starting to detect  ....\n\n");

  
    while(1) {


#if defined(PWAVE) 


           for (i=0;i<n_master;i++) {
        reg_addr=111; //to detect P-Wave
  	rc = modbus_read_registers(ctx[i],reg_addr-1,count, rxbuf[i]);
   	if (rc<0) continue;
    	
    	//dump_buf16(rxbuf[i],count);
      }

#elif defined(GSENSOR)


     for (i=0;i<n_master;i++) {

         reg_addr=102; //read G-Sensor b,c from palert A and Palert B
  	 rc = modbus_read_registers(ctx[i],reg_addr-1,2, rxbuf[i]);

   	// if (rc<0)  goto close;
       }


    a[0]=(short)rxbuf[0][0];  a[1]=(short)rxbuf[0][1];
    b[0]=(short)rxbuf[1][0];  b[1]=(short)rxbuf[1][1];
  
  
    fa[0]=a[0]*MagicNumber;  fa[1]=a[1]*MagicNumber;
    fb[0]=b[0]*MagicNumber; fb[1]=b[1]*MagicNumber;


//    fprintf(stderr,"===============>%12lf\t%12lf\t%12lf\t%12lf\t================\n",fa[0],fb[0],fa[1],fb[1]);

#endif




  //-----------------------------------------------------------------
#if defined(PWAVE) 
       printf("--->%d %d\n",rxbuf[0][0],rxbuf[1][0]);  
       if (rxbuf[0][0]>=4||rxbuf[1][0]>=4) {  // p-wave
#elif defined(GSENSOR)

     if ( fa[0]>=0.1 ||fb[0]>=0.1 || fa[1]>=0.1 ||fb[1]>=0.1) {  // 

#endif


          if (p_trigger==0) {
		p_trigger=1;
             fprintf(stderr,"buzzer.start..\n");

            }
          
 
      }  else  {
                 
        if (p_trigger==1) {   
           p_trigger=0;
           fprintf(stderr,"buzzer.stop..\n");
	  }	
            continue;
      }


//------------------------------------------------------------

#ifdef LOG_CAP 
 
     fprintf(stderr,"Starting to log data G-sensor\n\n");
   gettimeofday(&t0, 0); 
    while (p_trigger==1) {  // p-wav trigger
      
    
         
       for (i=0;i<n_master;i++) {

         reg_addr=102; //read G-Sensor b,c from palert A and Palert B
  	 rc = modbus_read_registers(ctx[i],reg_addr-1,2, rxbuf[i]);

   	// if (rc<0)  goto close;
       }


    a[0]=(short)rxbuf[0][0];  a[1]=(short)rxbuf[0][1];
    b[0]=(short)rxbuf[1][0];  b[1]=(short)rxbuf[1][1];
 //  fprintf(stderr,"%d\t%d\t%d\t%d\t\n",rxbuf[0][0],rxbuf[0][1],rxbuf[1][0],rxbuf[1][1]);
  
    fa[0]=a[0]*MagicNumber;  fa[1]=a[1]*MagicNumber;
    fb[0]=b[0]*MagicNumber; fb[1]=b[1]*MagicNumber;
 
    

    fprintf(stderr,"%12lf\t%12lf\t%12lf\t%12lf\t\n",fa[0],fb[0],fa[1],fb[1]);

   fprintf(fp," %1f  %lf\n",fa[0],fb[0]);  
   fprintf(fp2," %lf  %lf\n",fa[1],fb[1]);  
     gettimeofday(&t1, 0);
     elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;

// fprintf(stderr,"%010u\t%12lf\t%12lf\n",  (unsigned int)elapsed,fa,fb);
 

   // LOG2( (unsigned int)t1.tv_sec*1000000+ (unsigned int)t1.tv_usec ,fa,fb);

   
     if (elapsed >n_second) {
        printf(" Log end ..STARTING OCTAVE.. \n\n");
        fflush(fp);   
        system("/root/palert/octave/pi.sh");
        p_trigger=0;
 
      
     } 
    
     usleep(20000);  //20ms polling time
     }  // endi while p-wav trigger
#endif 
//-----------------------------------------------------

     
      usleep(100);
   } 

close:

  fprintf(stderr,"******Program Exit!!!******* \n\n");
  /* Close the connection */
   for (i=0;i<n_master;i++) {
    modbus_close(ctx[i]);
    modbus_free(ctx[i]);
   }
   fflush(fp);
   fclose(fp);
   fflush(fp2);
   fclose(fp2);
    return 0;
}

void do_exit(int sig)
{
    #ifdef IT_PROJ
       kill(buzzer_pid,SIGUSR1);
    #endif



   fprintf(stderr,"******Program Exit!!!******* \n\n");
   exit(0);
}


void reap_child(int sig)
{

   wait(NULL);

}
void dump_buf16( uint16_t *buf,int len)
{
  int i=0;

  for (i=0;i<len;) {
     fprintf(stdout,"0x%X ",buf[i]);
    if (++i%16==0) printf("\n");
   }
  printf("\n");

}

void show_usage()
{
     printf("Usage:\n");
     printf(" ./palert <IP1> <IP2>\n");
  
     exit(1);
}





